<template>
  <!-- 购物车 -->
    <div class="cart-view">
      <!-- 导航条 -->
      <van-sticky>
            <base-nav :show-right="false" title="购物车"></base-nav>
        </van-sticky>
        <div class="cart-list">
            <!-- 购物车为空显示图片 -->
            <div class="cart-ko" v-show="userStore.userCartList.length ==0">
              <img src="https://gd-hbimg.huaban.com/046d6ff46be5dae8da0ebf8ce3c1237955af817baae9-KgQqTi_fw658" alt="">
            </div>
            <!-- 购物车列表 -->
             <div v-for="item in userStore.userCartList" :key="item.goods_id">
              <van-swipe-cell >
                <van-checkbox class="left-check" v-model="item.isChecked"></van-checkbox>
                  <van-card
                  :price="item.price"
                  :desc="item.goods_desc"
                  :title="item.goods_name"
                  class="goods-card"
                  :thumb="item.goods_thumb"
                >
                  <template #num>
                    <van-stepper @change="numberChange" v-model="item.goods_number"  min="1" max="10" disable-input :name="item.goods_id"/>
                  </template>
                </van-card>
                <template #right>
                  <van-button @click="del(item)" square text="删除" type="danger" class="delete-button" />
                </template>
            </van-swipe-cell>
            <van-divider :style="{borderColor: '#ccc'}"></van-divider>
             </div>
           

          
        </div>
        <van-divider
          :style="{ color: '#000', borderColor: '#000', padding: '0 16px' }"
        >
          猜你喜欢
        </van-divider>
        <div class="goods-list">
            <goods v-for="item in likeList" :goods="item" :key="item.goods_id"></goods>
            

        </div>
        <van-submit-bar button-color="#000" style="border-radius: 0px;" :price="priceALL"  @submit="onSubmit" button-text="提交订单">
          <van-checkbox @change="checkedAllbnt" v-model="checkedAll">全选</van-checkbox>
         
        </van-submit-bar>
    </div>
</template>
<script setup lang="ts">
  import { useUserStore } from '../../store';
  import Goods from '../../components/base/Goods.vue';
  import API from '../../api'

  let userStore = useUserStore();
  //调用购物车数据方法

	
	let router = useRouter();
  // 全选框
	let checkedAll = ref(false);
	// 当前商品数量状态 ID
	let changeGoodsId = ref('');

  let likeList = ref([]);


  // 钩子函数
  onMounted(async()=>{

   
    userStore.getUserCarData();
    //请求猜你喜欢数据
    let res = await API.getData('/api_goods',{page: parseInt(Math.random()*10+1) , pagesize: 4})
    likeList.value = res;
    

  });

  //计算总价
  let priceALL = computed(()=>{
    let all = 0;
    userStore.userCartList.forEach(item => {
      if(item.isChecked){
				all += item.price * parseInt(item.goods_number)
			};
    });

    return all * 100;
  });

  //全选方法
  let checkedAllbnt = val =>{
    userStore.userCartList.forEach(item => {
      item.isChecked = val;
    });
  };

  //点击加减 返回步进器值和绑定的name
  let numberChange = async (val,detail) =>{
    // console.log(val,detail);
    // 修改数据库商品数量
    let even = await API.getCarData('/api_cart',{
      status: 'addcart',
			userId: userStore.TOKEN,
			goodsId: detail.name,
			goodsNumber: val 
    })

  
  };

  // 删除购物车商品
  let del = async item =>{
    // 发起请求
    let even = await API.getCarData('/api_cart',{
      status: 'delcart',
			userId: userStore.TOKEN,
			goodsId: item.goods_id
    });

    if(even.code != 0){
      showFailToast('删除失败');
      return;
    }
    // console.log(even);
    showSuccessToast('删除成功');

    userStore.userCartList.splice(userStore.userCartList.indexOf(item), 1);
    
  };

  // 点击提交
  let onSubmit = async () =>{
    if(userStore.userCartList.length ==0){
      showFailToast('购物车为空');
			return;
    }
    // 用户选择中
		let userIsChecked = userStore.userCartList.some(item => item.isChecked == true);
    if(!userIsChecked){
			showFailToast('请选择商品');
			return;
		};
    let goodsIdString: string = '';  //'123&444&'
		userStore.userCartList.forEach(item => {
			if(item.isChecked){
				goodsIdString += item.goods_id + '&';
			}
		});

    //加入结算清单
		let res = await API.getSettlementData('/api_settlement', {
			status : 'addsettlement',
			userId : userStore.TOKEN,
			goodsId : goodsIdString.substr(0, (goodsIdString.length-1)),
			from : 'cart'
		});
		// console.log(res);
		if(res.code != 0){
			showFailToast('购买失败');
			return;
		}
		//跳转到地址
		router.push('/confirmorder');
  };

</script>
<style  lang="less">
    //购物车为空显示图片 
  .cart-ko{
    width: 100%;
     img{
      width: 100%;
     }
  }
  // 购物车列表
  .cart-list{

		box-sizing: border-box;
	}
  // 商品列表样式
	.van-swipe-cell__wrapper{
		  display: flex !important;
		// background: #F7F8FA;
		// 左侧选择框
		.left-check{
			padding-left: 10px;
		}
    // 商品卡牌
		.goods-card{
			width: 92%;
      background: white;
		}
		// 删除按钮
		.delete-button{
			height: 100%;
		}
	}
  
  // 底部提交
 
  .van-submit-bar{
	  bottom: 49px !important;
  }
  // 猜你喜欢
  .goods-list{
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        padding: 0px 10px;
    }

</style>